#include <iostream>
#include <signal.h>
#include <unistd.h>
#include <vector>
#include <functional>
using namespace std;

using func_t = function<void()>;
vector<func_t> g_cleaner;
int gcount = 0;

void hander(int signal)
{
    for (auto f : g_cleaner)
    {
        f();
    }
    cout << "gcount: " << gcount << endl;
    int n = alarm(5); // 重新设置闹钟，返回上一次闹钟的剩余时间
    cout << "alarm reset :" << n << endl;
}
void alarm_cancel(int signal)
{
    alarm(0); // 取消闹钟
    cout << "alarm canceled" << endl;
}
int main()
{
    cout << "My PID is " << getpid() << endl;
    g_cleaner.push_back([]()
                        { cout << "我是一个内核刷新操作" << endl; });
    g_cleaner.push_back([]()
                        { cout << "我是一个检测进程时间片的操作，如果时间片到了，我会切换进程" << endl; });
    g_cleaner.push_back([]()
                        { cout << "我是一个内存管理操作，定期清理操作系统内部的内存碎片" << endl; });

    signal(SIGALRM, hander);
    signal(SIGINT, alarm_cancel);
    alarm(5);
    while (true)
    {
        pause();
        cout << "我醒来了..." << endl;
        gcount++;
    }
}

